package org.example.algorithm.bst;

import org.example.algorithm.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class IsValidBSTSolution {

    public static void main(String[] args) {

    }

    //非递归写法
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        long min = Long.MIN_VALUE;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (!stack.isEmpty() || cur != null) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode node = stack.pop();
            if (node.val <= min) {
                return false;
            }
            min = node.val;
            cur = node.right;
        }
        return true;
    }

    //递归
    public boolean isValidBST3(TreeNode root) {
        return doValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    private boolean doValidBST(TreeNode root, long min, long max) {
        if (root == null) {
            return true;
        }
        if (root.val <= min || root.val >= max) {
            return false;
        }
        return doValidBST(root.left, min, root.val) && doValidBST(root.right, root.val, max);
    }

    //先序遍历获取列表，判断是否严格递增
    public boolean isValidBST2(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        doTraverse(root, list);
        for (int i=1;i<list.size();i++) {
            if (list.get(i) <= list.get(i-1)) {
                return false;
            }
        }
        return true;
    }

    private void doTraverse(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        doTraverse(root.left, list);
        list.add(root.val);
        doTraverse(root.right, list);
    }
}
